package com.da.lon.wang.xlg.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.beawise.wssdk.WSManager;
import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.bean.NewHomeBean;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.fragment.CartFragment;
import com.da.lon.wang.xlg.fragment.ClassyFragment;
import com.da.lon.wang.xlg.fragment.HomeFragment;
import com.da.lon.wang.xlg.fragment.MineFragment;
import com.da.lon.wang.xlg.fragment.NewPartyFragment;
import com.da.lon.wang.xlg.fragment.PartyFragment;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.util.ExampleUtil;
import com.da.lon.wang.xlg.util.LogUtils;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.osell.selection.ui.common.SettingActivity;
import com.umeng.analytics.MobclickAgent;
import com.zxing.android.CaptureActivity;

import java.util.ArrayList;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;


public class HomeActivity extends FragmentActivity implements OnClickListener,
        OnCheckedChangeListener {

    public final static String WS_ON_ENTER_REGION = "com.beawise.wssdk.broadcast.action.ENTER_REGION";
    public final static String WS_ON_EXIT_REGION = "com.beawise.wssdk.broadcast.action.EXIT_REGION";
    public final static String WS_ON_REGION_TYPE = "ws_region_type";
    public final static int WS_REGION_UNKNOWN = 0;
    public final static int WS_REGION_GATE = 1;
    public final static int WS_REGION_REST = 2;
    public final static int WS_REGION_RACK = 3;
    public final static int WS_REGION_CASHER = 4;
    public final static int WS_REGION_HOTSPOT = 5;
    protected static final String TAG = "HomeActivity";
    private static final int MSG_SET_ALIAS = 1001;
    public static String uploadType = "default";
    public static int uploadMaxNum = 8;
    FragmentTransaction ft;
    RelativeLayout home_network;
    ConnectionChangeReceiver mReceiver;
    Handler goToHomeHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    LogUtils.v("Set alias in handler");
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj, null, mAliasCallback);
                    break;
                default:
                    break;
            }
            // gotoHome();
        }

        ;
    };
    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    LogUtils.v(logs);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LogUtils.v(logs);
                    goToHomeHandler.sendMessageDelayed(
                            goToHomeHandler.obtainMessage(MSG_SET_ALIAS, alias),
                            1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    LogUtils.v(logs);
            }
        }
    };
    private long firstTime = 0;
    private HomeFragment homeFragment;
    private PartyFragment partyFragment;
    private CartFragment cartFragment;
    private MineFragment mineFragment;
    private ClassyFragment classyFragment;
    private RadioGroup bottomGroup;
    private Context context;
    private HttpLoader<NewHomeBean> loader;
    private ImageButton topleftButton;
    private ImageButton topleftButton2;
    private ImageButton toprightButton;
    private TextView toptitleTextView;
    private RelativeLayout topRelativeLayout;
    private ArrayList<Fragment> arrayList;
    private FragmentManager manager;
    private FragmentTransaction transaction;
    private int index;
    private NewPartyFragment newPartyFragment;
    private BroadcastReceiver mRegionBroadcast = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            int type = intent.getIntExtra(WS_ON_REGION_TYPE, WS_REGION_UNKNOWN);
            if (XLGConstants.TAGANDALIAS_RECEIVED_ACTION.equals(action)) {
                setAlias();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ocoffee_home);
        context = this;
        IntentFilter filter = new IntentFilter();
        filter.addAction(WS_ON_ENTER_REGION);
        filter.addAction(WS_ON_EXIT_REGION);
        filter.addAction(XLGConstants.TAGANDALIAS_RECEIVED_ACTION);
        registerReceiver(mRegionBroadcast, filter);
        setAlias();
        initView();
        registerReceiver();
        arrayList = new ArrayList<>();
        if (arrayList.size() == 0) {
            homeFragment = new HomeFragment();
            arrayList.add(homeFragment);

            newPartyFragment = new NewPartyFragment();
            arrayList.add(newPartyFragment);

            classyFragment = new ClassyFragment();
            arrayList.add(classyFragment);

            cartFragment = new CartFragment();
            arrayList.add(cartFragment);

            mineFragment = new MineFragment();
            arrayList.add(mineFragment);
        }
        manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();
        transaction.add(R.id.content, arrayList.get(0));
        transaction.addToBackStack(null);
        transaction.commit();

        try {
            if ("on".equals(PreferenceUtils.getInstance().getSettingStr(
                    "WSManager", ""))) {
                WSManager.getInstance(HomeActivity.this).startWork("1",
                        MyApplication.getUserName(), true);
                PreferenceUtils.getInstance().SetSettingString("WSManager",
                        "on");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private void initView() {
        bottomGroup = (RadioGroup) findViewById(R.id.bottom_rg);
        bottomGroup.setOnCheckedChangeListener(this);

        topRelativeLayout = (RelativeLayout) findViewById(R.id.ocoffee_top_rl);

        topleftButton = (ImageButton) findViewById(R.id.ocoffee_top_left);
        topleftButton2 = (ImageButton) findViewById(R.id.ocoffee_top_left2);
        toprightButton = (ImageButton) findViewById(R.id.ocoffee_top_right);
        toptitleTextView = (TextView) findViewById(R.id.ocoffee_top_title);
        toptitleTextView.setText("徐州欧咖");
        topleftButton.setOnClickListener(this);
        topleftButton2.setOnClickListener(this);
        toprightButton.setOnClickListener(this);

        home_network = (RelativeLayout) findViewById(R.id.home_network);
        home_network.setAlpha(0.7f);
        home_network.setOnClickListener(this);
        TelephonyManager tm = (TelephonyManager) this
                .getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = tm.getDeviceId();
        PreferenceUtils.getInstance().SetSettingString(
                PreferencesConfig.DEVICE_ID, deviceId);

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        transaction = manager.beginTransaction();
        switch (checkedId) {
            case R.id.home:
                toptitleTextView.setText("徐州欧咖");
                topleftButton.setVisibility(View.VISIBLE);
                toprightButton.setVisibility(View.VISIBLE);
                topleftButton2.setVisibility(View.GONE);

                topRelativeLayout.setVisibility(View.VISIBLE);

                if (index != 0) {
                    index = 0;
                    if (arrayList.size() == 0) {
                        transaction.add(R.id.content, arrayList.get(0));
                    } else {
                        transaction.replace(R.id.content, arrayList.get(0));
                    }

                    transaction.commit();
                }

                break;
            case R.id.party:
                toptitleTextView.setText("活动");
                topleftButton.setVisibility(View.INVISIBLE);
                toprightButton.setVisibility(View.INVISIBLE);
                topleftButton2.setVisibility(View.GONE);
                topRelativeLayout.setVisibility(View.VISIBLE);

                if (index != 1) {
                    index = 1;
                    if (arrayList.size() == 0) {
                        transaction.add(R.id.content, arrayList.get(1));
                    } else {
                        transaction.replace(R.id.content, arrayList.get(1));
                    }

                    transaction.commit();
                }
                break;
            case R.id.classy:
                toptitleTextView.setText("分类");
                topleftButton.setVisibility(View.INVISIBLE);
                toprightButton.setVisibility(View.INVISIBLE);
                topleftButton2.setVisibility(View.GONE);
                topRelativeLayout.setVisibility(View.VISIBLE);

                if (index != 2) {
                    index = 2;
                    if (arrayList.size() == 0) {
                        transaction.add(R.id.content, arrayList.get(2));
                    } else {
                        transaction.replace(R.id.content, arrayList.get(2));
                    }

                    transaction.commit();
                }
                break;
            case R.id.cart:
                toptitleTextView.setText("购物车");
                topleftButton.setVisibility(View.INVISIBLE);
                toprightButton.setVisibility(View.INVISIBLE);
                topleftButton2.setVisibility(View.GONE);
                topRelativeLayout.setVisibility(View.VISIBLE);

                if (index != 3) {
                    index = 3;
                    if (arrayList.size() == 0) {
                        transaction.add(R.id.content, arrayList.get(3));
                    } else {
                        transaction.replace(R.id.content, arrayList.get(3));
                    }

                    transaction.commit();
                }
                break;

            case R.id.mine:
                toptitleTextView.setText("我的欧咖");
                topleftButton.setVisibility(View.GONE);
                toprightButton.setVisibility(View.INVISIBLE);
                topleftButton2.setVisibility(View.VISIBLE);

                if (index != 4) {
                    index = 4;
                    if (arrayList.size() == 0) {
                        transaction.add(R.id.content, arrayList.get(4));
                    } else {
                        transaction.replace(R.id.content, arrayList.get(4));
                    }

                    transaction.commit();
                }
                break;

            default:
                break;
        }

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.ocoffee_top_left:
                if (!MyApplication.isNetworkAvailable(context)) {
                    return;
                }
                Intent intent = new Intent(this, HotSearchActivity.class);
                startActivity(intent);

                break;
            case R.id.ocoffee_top_right:
                if (!MyApplication.isNetworkAvailable(context)) {
                    return;
                }
                Intent ewmIntent = new Intent(context, CaptureActivity.class);
                startActivity(ewmIntent);

                break;

            case R.id.ocoffee_top_left2:
                if (!MyApplication.isNetworkAvailable(context)) {
                    return;
                }
                String userId = PreferenceUtils.getInstance().getSettingStr(
                        PreferencesConfig.USER_ID, "");
                if (userId != null && !"".equals(userId)) {
                    Intent intent2 = new Intent(this, SettingActivity.class);
                    startActivity(intent2);
                } else {
                    intent = new Intent(context, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.home_network:
                MyApplication.openSystemSetting(this);
                break;
            default:
                break;
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub

        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                exit();
                return true;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void setAlias() {
        String alias = "qqg_" + MyApplication.getUserId();
        LogUtils.v(alias);
        if (TextUtils.isEmpty(alias)) {
            Toast.makeText(HomeActivity.this, R.string.error_alias_empty,
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (!ExampleUtil.isValidTagAndAlias(alias)) {
            Toast.makeText(HomeActivity.this, R.string.error_tag_gs_empty,
                    Toast.LENGTH_SHORT).show();
            return;
        }
        // 调用JPush API设置Alias
        goToHomeHandler.sendMessage(goToHomeHandler.obtainMessage(
                MSG_SET_ALIAS, alias));
    }

    private void exit() {
        // TODO Auto-generated method stub
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            Toast.makeText(HomeActivity.this, "再按一次返回键退出徐州欧咖", Toast.LENGTH_SHORT)
                    .show();
            firstTime = secondTime;
        } else {
            if (!"off".equals(PreferenceUtils.getInstance().getSettingStr(
                    "WSManager", ""))) {
                WSManager.getInstance(HomeActivity.this).stopWork();
            }

            this.unregisterReceiver(mReceiver);
            System.exit(0);
            finish();
        }
    }


    private void registerReceiver() {
        IntentFilter filter = new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION);
        mReceiver = new ConnectionChangeReceiver();
        this.registerReceiver(mReceiver, filter);
    }


    public class ConnectionChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mobNetInfo = connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            NetworkInfo wifiNetInfo = connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (null != mobNetInfo && null != wifiNetInfo
                    && !mobNetInfo.isConnected()
                    && !wifiNetInfo.isConnected()) {
                home_network.setVisibility(View.VISIBLE);
            } else {
                home_network.setVisibility(View.GONE);
            }


        }
    }

}